'use strict';

import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import * as actions from '../../actions/ring_tags_step2';
import { Button,Search,Notice,Icon,Dialog,Loading} from 'qnui';
import { Row, Col } from 'qnui/lib/grid';
import Breadcrumb from 'qnui/lib/breadcrumb'
import Step, { Item as StepItem } from 'qnui/lib/step';
import Form from 'qnui/lib/form';
import Field from 'qnui/lib/field';
import Input from 'qnui/lib/input';
import Radio,{ Group as RadioGroup } from 'qnui/lib/radio';
import DatePicker, { RangePicker } from 'qnui/lib/date-picker';
import ZhekouTags from 'components/zhekou-tags/index';
import './index.scss';

const FormItem = Form.Item;
class RingTagsStep2 extends React.Component {
    constructor(props) {
        super(props);
		this.dispatch = this.props.dispatch;
        this.state = {
			overlayVisible:false,
            value: null,
			search:"",
			hasTag:false,
			isSelectTag:false,
			refreshDialog:false,
			refreshContent:"",
			disableStartTime:false,
			disableEndTime:false,
			act_type:this.props.location.query.act_type
        };
		this.field = new Field(this, {
				scrollToFirstError:true,
				onChange: (name, value) => {
					if(name!="tagName"){
						this.setState({overlayVisible:false});
					}
					if(this.field.getState(name)=="success"){
						this.props.dispatch(actions.setField(name,value));
					}
				}
			});
		
		const tagTask = (this.props.location.state);
		if(tagTask){
			this.dispatch(actions.tagTaskWell());
			this.field.setValue("startTime",tagTask.tag_start_time);
			this.field.setValue("endTime",tagTask.tag_end_time);
			this.field.setValue("task_id",tagTask.task_id);
			this.field.setValue("task_tag_id",tagTask.tag_id);
			this.field.setValue("task_tag_name",tagTask.tag_name);
			this.field.setValue("notice","人群ID为"+tagTask.tag_id+"的"+(this.state.act_type=="limit"?"限购":"普通")+"折扣");
			this.state.disableStartTime=true;
			this.state.disableEndTime=true;
		}else{
			this.dispatch(actions.tagTaskError());
		}
    }
	setTag(tagName){
		this.setState({isSelectTag:true});
		this.props.dispatch(actions.setField("tagName",tagName));
		this.field.setValues({"tagName":tagName});
	}
	searchResult(hasTag,isPrefect){
		this.setState({"hasTag":hasTag,"isPrefect":isPrefect});
	}
	checkTag(rule,tagName,callback){
		this.setState({"search":tagName});
		if(this.state.isSelectTag){
			callback()
		}else{
			callback("请您从列表中选择标签！不可输入后直接提交")
		}
	}
    onVisibleChange = (visible) => {
        this.setState({
            overlayVisible:visible,
			isSelectTag:false
        });
    }
	checkEndDate(rule,date,callback){
		if(!date){
			callback('必须有一个结束时间');
		}
		if (date && Date.parse(date) < Date.parse(this.field.getValue('startTime'))) {
            callback('结束时间必须晚于开始时间！');
        } 
		if (date && Date.parse(date) < Date.parse(new Date())) {
            callback('结束时间必须晚于当前系统时间！');
        } 
		{
            callback();
        }
	}
	clickAmount(){
		this.field.setValue("discountRate","");
		this.field.reset("discountRate");
		this.props.dispatch(actions.setField("discountRate",""));
		this.props.dispatch(actions.setZhekouType("decreaseAmount"));
	}
	clickRate(){
		this.field.setValue("decreaseAmount","");
		this.field.reset("decreaseAmount");
		this.props.dispatch(actions.setField("decreaseAmount",""));
		this.props.dispatch(actions.setZhekouType("discountRate"));
	}
	checkLimit(rule,val,callback){
		const itemarea = this.field.getValue("itemArea");
		const amountEx = new RegExp(/^\d+$/);
		if(itemarea=="all" && !amountEx.test(val)){
			callback('请输入整数');
		}else{
			callback();
		}
	}
	checkAmount(rule,val,callback){
		const itemarea = this.field.getValue("itemArea");
		const amountEx = new RegExp(/^\d+(\.([1-9]|\d[1-9]))?$/);
		const zType = this.props.ring_tags_step2.zType
		if(itemarea=="all" && !amountEx.test(val) && zType=="decreaseAmount"){
			callback('支持2位小数，末尾不为0');
		}else{
			callback();
		}
	}
	checkRate(rule,val,callback){
		const itemarea = this.field.getValue("itemArea");
		const rateEx = new RegExp(/^\d{1}(\.([1-9]|\d[1-9]))?$/);
		const zType = this.props.ring_tags_step2.zType
		if(itemarea=="all" && !rateEx.test(val) && zType=="discountRate"){
			callback('请输入0.01-9.99');
		}else{
			callback();
		}
	}
	handleSubmit(e) {
        e.preventDefault();
		const ts = Date.parse(new Date())/1000;
		if(parseInt(window.info.timestemp)+1700 < ts){
			// 操作授权超过半小时，请重新授权
			let _self = this;
			// window.parent.closeRefreshDialog();  iframe页面调用该关闭方式
			window.closeRefreshDialog = (info)=>{
				window.info = info; //刷新已授权的信息
				_self.setState({"refreshDialog":false});
			}
			this.setState({"refreshDialog":true,"refreshContent":{"title":"敏感操作授权超时","msg":"请授权并在30分钟以内完成创建折扣。","content":<iframe name="showLogin" id="showLogin" style={{border:"none",height:"360px",width:"100%"}}  scrolling="no" src={"https://oauth.taobao.com/authorize?client_id=21127968&redirect_uri=http%3A%2F%2Fllxl.hz.taeapp.com%2F?a=refresh&response_type=code&state=llxl.hz.taeapp.com.21127968&view=web&ts="+ts} />}});
			return;
		}
        this.field.validate((errors, values) => {
            if (errors) {
                return;
            }
			
			if(window.info.deadline_time < Date.parse(values.endTime)/1000){
				//截至时间不能晚于订购时间，请重新设置
				this.setState({"refreshDialog":true,"refreshContent":{"title":"订购时间不足，活动截止时间不能晚于订购时间","msg":"","content":<a target="_blank" href="https://fuwu.taobao.com/ser/detail.htm?service_code=FW_GOODS-1840332"><Button type="primary" size="large" shape="warning">续费</Button></a>}});
				return;
			}
			
			values.endTime = Date.parse(values.endTime)/1000;
			values.startTime = Date.parse(values.startTime)/1000;
			if(this.state.act_type=="limit"){
				this.props.dispatch(actions.createLimitZhekou(values));
			}else{
				switch(this.field.getValue("itemArea")){
					case "all":
						this.props.dispatch(actions.createShopZhekou(values));
					break;
					case "some":
						this.props.dispatch(actions.createItemZhekou(values));
					break;
				}
			}
        });
    }
	componentWillReceiveProps(nextProps){
		if(nextProps.ring_tags_step2.needItems){
			nextProps.dispatch(actions.stepNeedItems());
			nextProps.history.pushState(null, '/ring_tags_step3?is_edit=&act_type='+this.state.act_type+'&activity_id='+nextProps.ring_tags_step2.activityId+"&tag_id="+this.field.getValue("task_tag_id"));
		}
		if(nextProps.ring_tags_step2.actionDone){
			nextProps.history.pushState(null, '/ring_tags');
		}
	}
	onClose(){
		if(this.props.ring_tags_step2.noTask){
			this.props.history.pushState(null, '/ring_tags');
		}else{
			this.props.dispatch(actions.closeDialog());
		}
	}
	onRefreshClose(){
		this.setState({"refreshDialog":false});
	}
  render() {
	const tags = <ZhekouTags
					setTag={this.setTag.bind(this)}	
					curTag={this.props.ring_tags_step2.tagName}
					search={this.state.search}
					searchResult={this.searchResult.bind(this)}
					/>
	const init = this.field.init;
	const formItemLayout = {
		labelCol: {fixedSpan: 6},
		wrapperCol: {fixedSpan: 30},
	};
	const date = new Date();
	const defaultNotice = date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日设置的折扣";
	const step3 = this.field.getValue("itemArea")=="all"?"":<StepItem title="选择商品" />;
	const loginBtn = this.props.ring_tags_step2.loginError?
						<a href="https://oauth.taobao.com/authorize?response_type=code&client_id=21127968&redirect_uri=http://llxl.hz.taeapp.com/?state=ring_tags_step2&view=web"><Button size="large" type="primary"><span>请重新登陆</span></Button></a>
					 :"";
    const footer = this.props.ring_tags_step2.loginError?<div>{loginBtn}</div>:"";
	const creatingTitle = this.props.ring_tags_step2.creating?"正在创建。。。":"错误信息";
	const creatingMsg = this.props.ring_tags_step2.creating?<Loading />:this.props.ring_tags_step2.message;
	const creatingDialog = this.props.ring_tags_step2.creating?true:this.props.ring_tags_step2.error;

	const actionSet = 
					<div>
					<FormItem
						label="活动范围"
						required 
						{...formItemLayout}>
						<RadioGroup {...init('itemArea', {initValue: 'some',rules: [{required: true}]})} >
							{/*<Radio id="all" value="all">全部商品</Radio> 全店折扣已下线*/}
							<Radio id="some" value="some">部分商品</Radio>
						</RadioGroup>
					</FormItem>	
					<FormItem
						style={{display:(this.props.ring_tags_step2.itemArea=="all")?"block":"none"}}
						label="优惠设置" 
						className="zheSet"
						{...formItemLayout}>
							<Row justify="start">
								<FormItem style={{width:"150px"}}>
									<Input 
										style={{width:"130px"}}
										size="large" 
										addonBefore="打" 
										{...init('discountRate', {
											rules:[{validator:this.checkRate.bind(this)}]
										})}
										state={this.props.ring_tags_step2.zType=="discountRate"?"success":""}
										onClick={this.clickRate.bind(this)}
										addonAfter="折" 
									/>
								</FormItem>
								<FormItem style={{width:"150px"}}>
									<Input 
										style={{width:"130px"}}
										size="large" 
										addonBefore="减" 
										{...init('decreaseAmount', {
											rules:[{validator:this.checkAmount.bind(this)}]
										})}
										state={this.props.ring_tags_step2.zType=="decreaseAmount"?"success":""}
										onClick={this.clickAmount.bind(this)}
										addonAfter="元" 
									/>
								</FormItem>
								<Input htmlType="hidden" 
									{...init('task_id',{initValue:""})}
								/>
								<Input htmlType="hidden" 
									{...init('task_tag_id',{initValue:""})}
								/>
								<Input htmlType="hidden" 
									{...init('task_tag_name',{initValue:""})}
								/>
							</Row>
					</FormItem>
					</div>;
	return (
        <div className="page1-page">
			<Dialog
					visible = {this.state.refreshDialog}
                    onOk = {this.onRefreshClose.bind(this)}
                    onCancel = {this.onRefreshClose.bind(this)}
                    onClose = {this.onRefreshClose.bind(this)} 
					title = {this.state.refreshContent.title}
					style={{width:"445px",height:"360px"}}
					footer = {false}
					>
					<Row justify="center">
						{this.state.refreshContent.msg}
					</Row>
					<Row justify="center">
						{this.state.refreshContent.content}
					</Row>
            </Dialog>
			<Dialog style={{width:"600px",height:"360px"}} 
					visible = {creatingDialog}
                    onOk = {this.onClose.bind(this)}
                    onCancel = {this.onClose.bind(this)}
                    onClose = {this.onClose.bind(this)} 
					title = {creatingTitle}
					footer = {footer}
					>
					<Row justify="center">
						<h3>{creatingMsg}</h3>
					</Row>
            </Dialog>
          <Row style={{background:"#F6F6F6",margin:"3px 0"}} justify="start">
			<Col span="8" align="center">
			<Breadcrumb maxNode={5}>
				  <Breadcrumb.Item>连环折扣</Breadcrumb.Item>
				  <Breadcrumb.Item>创建</Breadcrumb.Item>
				  <Breadcrumb.Item>设置折扣</Breadcrumb.Item>
			  </Breadcrumb>
			</Col>
			<Col offset="2">
					<Step current={1} type="dot">
						<StepItem title="设置标签" />
						<StepItem title="创建折扣"/>
						{step3}
						<StepItem title="完成"/>
					</Step>
			</Col>
		  </Row>
          <Row justify="start" style={{marginTop:"50px"}}>
		   <Form direction="ver"  size="large" field={this.field}>
            <Col span="21">
			  <FormItem label="折扣标签"  required {...formItemLayout}>
				<Search placeholder="选择标签"
					 type="normal"
					 {...init('tagName', {rules: [{validator:this.checkTag.bind(this)}]})}
					 combox={tags}
					 overlayVisible={this.state.overlayVisible}
					 onInputFocus={this.onVisibleChange.bind(this,true)}
					 hasIcon={false}
					 searchText="　"
					 autoWidth
					 className="tagSearch"
					 onSearch={()=>{}}
					 />
			  </FormItem>
			  <FormItem
					label="时间设置"
					{...formItemLayout}>
					<Row>
                        <FormItem required label="开始"><DatePicker disabled={this.state.disableStartTime} size="large" {...init('startTime',{rules: [{required: true,message:"请设置开始时间"}]})} showTime/></FormItem>
						<FormItem required label="结束"><DatePicker disabled={this.state.disableEndTime} size="large" {...init('endTime',{rules: [{validator:this.checkEndDate.bind(this)}]})} showTime/></FormItem>
                    </Row>
			  </FormItem>
			  <FormItem
					label="活动备注"
					required 
					{...formItemLayout}>
					<Input size="large" className="notice" placeholder="备注" {...init('notice', {
								initValue:defaultNotice,
								rules: [
                                {required: true,whitespace:true, message: '真的不打算写点什么吗？'},
								],
							})}  />
			  </FormItem>
			  {this.state.act_type=="limit"?"":actionSet}
			  <FormItem
					label=""
					{...formItemLayout}>
						<Link to="ring_tags">
							<Button  size="large" type="normal">
								<span>取消创建</span>
							</Button>
						</Link>
						<Button htmlType="submit" onClick={this.handleSubmit.bind(this)} style={{marginLeft:"20px"}} size="large" type="primary">
							创建活动
						</Button>
			  </FormItem>
			</Col>
		   </Form>
          </Row>
        </div>
    );
  }
}


export default connect((state)=> {
  return {
    ring_tags_step2: state.ring_tags_step2
  };
})(RingTagsStep2);
